import { Row, Col, Table } from 'antd'
import { useEffect, useState } from 'react'
import * as echarts from 'echarts'
import { paginationConfig } from '@/utils'


const TabHV = ({ HVdata, handleExport }) => {
  const [algor1, setAlgor1] = useState('')
  const [algor2, setAlgor2] = useState('')

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
    },
    {
      title: algor1 || '算法1',
      dataIndex: 'algor1',
      key: 'algor1',
      align: 'center',
      sorter: (a, b) => a.algor1 - b.algor1,
    },
    {
      title: algor2 || '算法2',
      dataIndex: 'algor2',
      key: 'algor2',
      align: 'center',
      sorter: (a, b) => a.algor2 - b.algor2,
    }
  ]

  // 表格数据
  const [tableData, setTableData] = useState([])
  const [w, setW] = useState(0)
  const [t, setT] = useState(0)
  const [l, setL] = useState(0)

  useEffect(() => {
    const chart = echarts.init(document.getElementById('myChart2'))

    if (HVdata) {
      const categories = [] // 用于存储所有结果的标签（例如："result1", "result2", ...）
      const seriesData = [] // 用于存储图表的系列数据
      const legendData = [] // 用于存储图表的图例数据
      const algorithmNames = Object.keys(HVdata) // 获取所有算法的名称
      setAlgor1(algorithmNames[0])
      setAlgor2(algorithmNames[1])


      // 填充数据
      let maxResults = 0 // 存储最大的结果数量

      // 计算最大结果数量并生成categories
      algorithmNames.forEach((algorithm) => {
        const resultKeys = Object.keys(HVdata[algorithm])
        maxResults = Math.max(maxResults, resultKeys.length)
        resultKeys.forEach((key, index) => {
          if (!categories.includes(`${index}`)) {
            categories.push(`${index}`)
          }
        })
      })



      // 根据算法生成seriesData和legendData
      algorithmNames.forEach((algorithm, index) => {
        const resultData = []
        for (let i = 0;i < maxResults;i++) {
          let key = ''
          if (i === 0) {
            key = `final.txt`
          } else {
            key = `result${i}.txt`
          }
          const value = HVdata[algorithm][key] || null // 使用null填充缺失的数据
          resultData.push(value)
        }
        seriesData.push({
          name: algorithm,
          type: 'bar',
          data: resultData,
          itemStyle: {
            // 根据算法索引动态分配颜色
            color: `hsl(${(360 / algorithmNames.length) * index}, 70%, 50%)`
          }
        })
        legendData.push(algorithm)
      })
      
      let w1 = 0
      let t1 = 0
      let l1 = 0

      const tData = []
      for (let i = 0;i < maxResults;i++) {
        let key = ''
        if (i === 0) {
          key = `final.txt`
        } else {
          key = `result${i}.txt`
        }
        const value1 = HVdata[algorithmNames[0]][key].toExponential(4)
        const value2 = HVdata[algorithmNames[1]][key].toExponential(4)
        const v1 = HVdata[algorithmNames[0]][key]
        const v2 = HVdata[algorithmNames[1]][key]
        console.log(w, t, l)
        let avg = (v1 + v2) / 2
        if (Math.abs(v1 - v2) / avg <= 0.05) {
          t1 += 1
        } else if (v1 > v2) {
          w1 += 1
        } else {
          l1 += 1
        }
        tData.push({
          id: i,
          algor1: value1,
          algor2: value2
        })
      }

      setW(w1)
      setT(t1)
      setL(l1)

      setTableData(tData)

      handleExport(tData, columns)

      // 配置图表
      const option = {
        title: {
          text: 'HV'
        },
        tooltip: {},
        legend: {
          data: legendData
        },
        xAxis: {
          data: categories
        },
        yAxis: {},
        series: seriesData,
        toolbox: {
          show: true,
          orient: "vertical",
          left: "left",
          top: "center",
          feature: {
            saveAsImage: {
              show: true,
              title: '保存为图片'
            },  // 保存图表
          },
        },
      }

      // 显示图表
      if (seriesData.length > 0) {
        chart.setOption(option)
      }
    }
  }, [HVdata])


  return (
    <div>
      <Row className='row'>
        <Col span={16}>
          <div className='myChart' id='myChart2'>
          </div>
        </Col>
        <Col span={8}>
          <div className='table'>
            {
              tableData.length > 0 && <Table
                bordered
                columns={columns}
                dataSource={tableData}
                pagination={
                  {
                    ...paginationConfig,
                    showQuickJumper: false,
                    position: ['bottomLeft']
                  }
                }
                scroll={{
                  x: 'max-content',
                  y: 'calc(100vh - 460px)',
                }}
                footer={() => (
                  <div style={{
                    textAlign: 'center'
                  }}>
                    {`w/t/l：${w}/${t}/${l}`}
                  </div>
                )}
              >

              </Table>
            }

          </div>
        </Col>

      </Row>
    </div>
  )
}

export default TabHV